<?php
declare (strict_types = 1);

namespace app\api\controller;

use app\BaseController;
use app\common\lib\Show;
use think\facade\Request;
use app\common\business\Cart as BusiCart;
use think\response\Redirect;

class Cart extends BaseController
{
    /**
     * 商品添加到购物车
     *
     * @return array
     */
    public function add()
    {
        $skuId = Request::param('id', 0, 'intval');
        $num   = Request::param('num', 1, 'intval');

        if (!$skuId || !$num) return Show::error('参数错误');

        $userId = (int) Request::header('userId');

        $busiCart = new BusiCart();
        $res      = $busiCart->addRedis($userId, $skuId, $num);
        if ($res === FALSE) Show::error();
        return Show::success();
    }

    /**
     * 购物车商品列表
     *
     * @return array
     */
    public function lists()
    {
        // 获取提交订单 ID 字符串
        $ids = Request::param('id', null, 'trim');

        $userId = (int) Request::header('userId');

        $busiCart = new BusiCart();
        $result   = $busiCart->lists($userId, $ids);
        if (!$result) return Show::error();
        return Show::success($result);
    }

    /**
     * 购物车商品删除
     *
     * @return array
     */
    public function delete()
    {
        $id = Request::param('id', 0, 'intval');
        if (!$id) return Show::error('参数错误');

        $userId = (int) Request::header('userId');

        $busiCart = new BusiCart();
        $result   = $busiCart->deleteRdis($userId, $id);
        return $result === FALSE ? Show::error() : Show::success('删除成功');
    }

    /**
     * 购物车商品修改
     *
     * @return array
     */
    public function update()
    {
        $id = Request::param('id', 0, 'intval');
        $num = Request::param('num', 0, 'intval');
        if (!$id || !$num) return Show::error('参数错误');

        $userId = (int) Request::header('userId');
        try {
            $busiCart = new BusiCart();
            $update   = $busiCart->updateRedis($userId, $id, $num);
        } catch (\Exception $e) {
            return Show::error($e->getMessage());
        }
        return $update === FALSE ? how::error('修改失败') : SShow::success([], '修改成功');
    }
}
